package com.v2future.sjt.collegecheckingattendance.fruit;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.event.adapter.ReleaseEventImgGridAdapter;
import com.v2future.sjt.collegecheckingattendance.event.bean.ReleaseEventImageBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ConditionTypeBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.FruitAddRequestBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ResearchLevelBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ResearchTypeBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.DateTimePickDialogUtil;
import com.v2future.sjt.collegecheckingattendance.widget.PopupWindowSelectDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 添加科研
 *
 * @author shijianting
 * @time 2016/4/20 18:57
 */
public class AddFruitResearchActivity extends MainActivity {

    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.btn_type)
    Button btnType;
    @Bind(R.id.btn_time)
    Button btnTime;
    @Bind(R.id.btn_level)
    Button btnLevel;
    @Bind(R.id.et_remark)
    EditText etRemark;
    @Bind(R.id.et_abstract)
    EditText etAbstract;
    @Bind(R.id.gv_release_images)
    GridView gvReleaseImages;

    /**
     * 奖惩级别弹出框
     */
    PopupWindowSelectDialog popupWindowSelectDialog;

    /**
     * 适配器装载图片的列表
     */
    List<ReleaseEventImageBean> imageDataList;

    /**
     * 图片展示适配器
     */
    ReleaseEventImgGridAdapter adapter;

    /**
     * 级别
     */
    private List<ResearchLevelBean> researchLevelBeanList;

    /**
     * 选中的级别
     */
    ResearchLevelBean selectLevel;

    /**
     * 类别
     */
    private List<ResearchTypeBean> researchTypeBeanList;

    /**
     * 选中的类别
     */
    ResearchTypeBean selectType;

    int REQUEST_IMAGE = 1001;

    private ConditionTypeBean conditionTypeBean;

    @Override
    public void init() {
        conditionTypeBean = (ConditionTypeBean) getIntent().getSerializableExtra(IntentKey.FRUIT_TYPE);
        imageDataList = new ArrayList<>();
        ReleaseEventImageBean bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_fruit_research);
        ButterKnife.bind(this);
        initTitleBack(null);
        setTitleText("增加科研");
        setRightText("完成", finishListener);
        gvReleaseImages.setOnItemClickListener(imageClickListener);
    }

    @Override
    public void initAfter() {
        adapter = new ReleaseEventImgGridAdapter(this, imageDataList);
        gvReleaseImages.setAdapter(adapter);
        doGetLevel();
        doGetType();
    }

    /**
     * 刷新图片
     */
    private void refreshImages(ArrayList<String> path){
        imageDataList.clear();
        ReleaseEventImageBean bean = null;
        for (int i=0;i<path.size();i++) {
            bean = new ReleaseEventImageBean();
            bean.setImageUrl(path.get(i).toString());
            imageDataList.add(bean);
        }
        bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                ArrayList<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path.size() > 0 ) {
                    imageUrls = path;//保存已选的图片路径
                    refreshImages(path);
                    showLoadingDialog();
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            compressImages();
                            cancelLoadingDialog();
                        }
                    }.start();
                }
            }
        }
    }

    /**
     * 获取级别
     */
    public void doGetLevel() {
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_RESEARCH_LEVEL));
        NetUtils.doGetRequest(this, params, new NetTaskListener<ResearchLevelResponeBean>() {

            @Override
            public void onSuccess(ResearchLevelResponeBean result) {
                researchLevelBeanList = result.getData();
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(ResearchLevelResponeBean result) {

            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccessCache(ResearchLevelResponeBean result) {

            }
        });
    }

    /**
     * 获取类别
     */
    public void doGetType() {
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_RESEARCH_TYPE));
        NetUtils.doGetRequest(this, params, new NetTaskListener<ResearchTypeResponeBean>() {

            @Override
            public void onSuccess(ResearchTypeResponeBean result) {
                researchTypeBeanList = result.getData();
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(ResearchTypeResponeBean result) {

            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccessCache(ResearchTypeResponeBean result) {

            }
        });
    }

    /**
     * 添加成长
     * @param bean 参数
     */
    private void doAddUserFruit(FruitAddRequestBean bean){
        BaseRequestParams params = new BaseRequestParams(this, formatUrlDo(Constants.PUBLISH_EVENT));
        params.setMultipart(true);
        params.addQueryStringParameter("type", "3");//3表示发布成长
        params.addQueryStringParameter("conditionDesc", bean.getContent());
        params.addQueryStringParameter("condtionTypeId", bean.getConditionType());
        params.addQueryStringParameter("conditionTitle", bean.getConditionTitle());
        params.addQueryStringParameter("conditionArea", bean.getConditionArea());
        params.addQueryStringParameter("conditionDesc", bean.getConditionDesc());
        params.addQueryStringParameter("researchSubjectId", bean.getResearchSubjectId());
        params.addQueryStringParameter("researchRemark", bean.getResearchRemark());
        params.addQueryStringParameter("researchDesc", bean.getResearchDesc());
        params.addQueryStringParameter("researchLevelId", bean.getResearchLevelId());
        params.addQueryStringParameter("conditionUnit", bean.getConditionUnit());
        params.addQueryStringParameter("conditionLevel", bean.getConditionLevel());
//        params.addQueryStringParameter("conditionDate", bean.getConditionDate());
        if (null != imageUrls && imageUrls.size() > 0) {
            for (int i=0;i<imageUrls.size();i++) {
                params.addQueryStringParameter("imageName"+i, urlEncode(imageUrls.get(i).toString()));
                params.addBodyParameter("imageBody"+i, imageFiles.get(i), null);
            }
        }
        NetUtils.doPostRequestWithFiles(this, params, new NetTaskListener<BaseResponseBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                showOneBtnDialog(getString(R.string.notice), "提交科研完成", getString(R.string.iknow), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_type, R.id.btn_time, R.id.btn_level})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_type:
                if (researchTypeBeanList == null || researchTypeBeanList.size() == 0) {
                    tip("获取类型信息错误");
                    doGetType();
                }
                else {
                    List<String> typeStrList = new ArrayList<>();
                    for (ResearchTypeBean s:researchTypeBeanList
                            ) {
                        typeStrList.add(s.getResearchSubjectName());
                    }
                    popupWindowSelectDialog = new PopupWindowSelectDialog(this, R.style.Dialog_sesseion, typeStrList, new PopupWindowSelectDialog.ClickListener() {
                        @Override
                        public void selecData(String date, int position) {
                            btnType.setText(date);
                            selectType = researchTypeBeanList.get(position);
                        }
                    });
                    popupWindowSelectDialog.setCancelable(true);
                    popupWindowSelectDialog.show();
                }
                break;
            case R.id.btn_time:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        AddFruitResearchActivity.this, null);
                dateTimePicKDialog.dateTimePicKDialog(btnTime);
                break;
            case R.id.btn_level:
                if (researchLevelBeanList == null || researchLevelBeanList.size() == 0) {
                    tip("获取级别信息错误");
                    doGetLevel();
                }
                else {
                    List<String> levetStrList = new ArrayList<>();
                    for (ResearchLevelBean s:researchLevelBeanList
                            ) {
                        levetStrList.add(s.getResearchLevelName());
                    }
                    popupWindowSelectDialog = new PopupWindowSelectDialog(this, R.style.Dialog_sesseion, levetStrList, new PopupWindowSelectDialog.ClickListener() {
                        @Override
                        public void selecData(String date, int position) {
                            btnLevel.setText(date);
                            selectLevel = researchLevelBeanList.get(position);
                        }
                    });
                    popupWindowSelectDialog.setCancelable(true);
                    popupWindowSelectDialog.show();
                }
                break;
        }
    }

    /**
     * 完成事件
     */
    private View.OnClickListener finishListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //输入验证
            if (TextUtils.isEmpty(etName.getText().toString())) {
                tip("请输入科研名称");
                return;
            }
            if (TextUtils.isEmpty(etAbstract.getText().toString())) {
                tip("请输入科研简介");
                return;
            }
            if (null == selectLevel) {
                tip("请选择科研级别");
                return;
            }
            if (null == selectType) {
                tip("请选择科研类别");
                return;
            }
            if (TextUtils.isEmpty(btnTime.getText().toString())) {
                tip("请选择科研时间");
                return;
            }
            FruitAddRequestBean bean = new FruitAddRequestBean();
            bean.setConditionType(conditionTypeBean.getConditonTypeId());
            bean.setConditionTitle(etName.getText().toString());
            bean.setResearchSubjectId(selectType.getResearchSubjectId());
            bean.setResearchLevelId(selectLevel.getResearchLevelId());
            bean.setResearchRemark(etRemark.getText().toString());
            bean.setResearchDesc(etAbstract.getText().toString());
            bean.setConditionDate(btnTime.getText().toString());
            showLoadingDialog();
            doAddUserFruit(bean);
        }
    };

    /**
     * 级别回复
     */
    public class ResearchLevelResponeBean extends BaseResponseBean implements Serializable {
        List<ResearchLevelBean> data;

        public List<ResearchLevelBean> getData() {
            return data;
        }

        public void setData(List<ResearchLevelBean> data) {
            this.data = data;
        }
    }

    /**
     * 类型回复
     */
    public class ResearchTypeResponeBean extends BaseResponseBean implements Serializable {
        List<ResearchTypeBean> data;

        public List<ResearchTypeBean> getData() {
            return data;
        }

        public void setData(List<ResearchTypeBean> data) {
            this.data = data;
        }
    }

    AdapterView.OnItemClickListener imageClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            if (dataList.get(position).getImageUrl() == null) {
            Intent intent = new Intent(AddFruitResearchActivity.this, MultiImageSelectorActivity.class);
            // whether show camera
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
            // max select image amount
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 4);
            // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
            // default select images (support array list)
            intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imageUrls);
            startActivityForResult(intent, REQUEST_IMAGE);
//            }
        }
    };
}
